//
//  YTRegisterViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/3.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTRegisterViewModel.h"
#import "YTUserLoginAPI.h"

@implementation YTRegisterViewModel

- (void)initialize {
    
    _phoneValidate = [RACObserve(self, phoneNum) map:[NSObject yt_validateStrWithLenght:5]];
    _passwordValidate= [RACObserve(self, password) map:[NSObject yt_validateStrWithLenght:6]];
    _verifyValidate = [RACObserve(self, verifyCode) map:[NSObject yt_validateStrWithLenght:6]];
    
    RACSignal *checkProtocolValidate = [RACObserve(self, isChecked) map:^id(NSNumber *state) {
        return state;
    }];
    
    _allValidate = [RACSignal combineLatest:@[_phoneValidate, _verifyValidate, _passwordValidate, checkProtocolValidate]
                                   reduce:^id (NSNumber *phoneValidate, NSNumber *verifyCodeValidate,
                                               NSNumber *passwordValidate, NSNumber *checked){
        return @(phoneValidate.boolValue && verifyCodeValidate.boolValue && passwordValidate.boolValue && checked.boolValue);
    }];
    // 倒计时
    RACSignal *(^counterSignal)(NSNumber *countDown) = ^RACSignal *(NSNumber *countDown) {
        RACSignal *timerSingal = [RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]];
        RACSignal *counterSignal = [[timerSingal scanWithStart:countDown reduce:^id(NSNumber *running, id next) {
            return @(running.integerValue - 1);
        }] takeUntilBlock:^BOOL(NSNumber *untilNum) {
            return untilNum.integerValue < 0;
        }];
        
        return counterSignal;
    };
    
    _sendVerifyCommand = [[RACCommand alloc] initWithEnabled:_phoneValidate signalBlock:^RACSignal *(id input) {
        RACSignal *requestSignal = [YTUserLoginAPI sendVerifyCode:self.phoneNum areaCode:[self.areaCode substringFromIndex:2]];
        return [[RACSignal combineLatest:@[counterSignal(@60), requestSignal]
                                  reduce:^id(NSNumber *countDown, NSDictionary *response){
            if ([response[@"resultCode"] integerValue] == 1001) {
                return @"获取验证码";
            }
            return countDown.integerValue != 0 ? [NSString stringWithFormat:@"(%zd)s后重试", countDown.integerValue] : @"重新发送";
        }] takeUntilBlock:^BOOL(NSString *title) {
            return [title isEqualToString:@"获取验证码"]; // 监测发送短信是否失败了
        }];
    }];
    
    _registerCommand = [[RACCommand alloc] initWithEnabled:_allValidate signalBlock:^RACSignal *(RACTuple *input) {
        return [YTUserLoginAPI registerWithPhoneNum:self.phoneNum areaCode:[self.areaCode substringFromIndex:2]
                                           password:self.password verifyCode:self.verifyCode
                                         inviteCode:self.inviteCode inLand:self.isChina];
    }];
}

@end
